#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <memory>
#include <chrono>
#include <thread>
#include <sstream>
#include <iomanip>

// 简化的消息结构
struct SimpleMessage {
    std::string fromUser;
    std::string content;
    std::string timestamp;
    
    SimpleMessage(const std::string& from, const std::string& cnt) 
        : fromUser(from), content(cnt) {
        auto now = std::chrono::system_clock::now();
        auto time = std::chrono::system_clock::to_time_t(now);
        std::stringstream ss;
        ss << std::put_time(std::localtime(&time), "%H:%M:%S");
        timestamp = ss.str();
    }
};

// 私聊结构
struct PrivateChat {
    std::string chatId;
    std::string user1;
    std::string user2;
    std::vector<SimpleMessage> messages;
    
    PrivateChat(const std::string& u1, const std::string& u2) 
        : user1(u1), user2(u2) {
        if (u1 < u2) {
            chatId = u1 + "_" + u2;
        } else {
            chatId = u2 + "_" + u1;
        }
    }
};

// 群组结构
struct GroupChat {
    std::string groupId;
    std::string groupName;
    std::string ownerId;
    std::unordered_set<std::string> members;
    std::vector<SimpleMessage> messages;
    
    GroupChat(const std::string& id, const std::string& name, const std::string& owner)
        : groupId(id), groupName(name), ownerId(owner) {
        members.insert(owner);
    }
};

// 简化的聊天系统
class ChatComparison {
private:
    std::unordered_map<std::string, bool> users;
    std::unordered_map<std::string, std::shared_ptr<PrivateChat>> privateChats;
    std::unordered_map<std::string, std::shared_ptr<GroupChat>> groupChats;
    int groupCounter = 1000;
    
public:
    void addUser(const std::string& username) {
        users[username] = true;
    }
    
    std::string startPrivateChat(const std::string& user1, const std::string& user2) {
        std::string chatId = (user1 < user2) ? user1 + "_" + user2 : user2 + "_" + user1;
        if (privateChats.find(chatId) == privateChats.end()) {
            privateChats[chatId] = std::make_shared<PrivateChat>(user1, user2);
        }
        return chatId;
    }
    
    void sendPrivateMessage(const std::string& from, const std::string& to, const std::string& content) {
        std::string chatId = startPrivateChat(from, to);
        privateChats[chatId]->messages.emplace_back(from, content);
    }
    
    std::string createGroup(const std::string& groupName, const std::string& owner) {
        std::string groupId = "group_" + std::to_string(groupCounter++);
        groupChats[groupId] = std::make_shared<GroupChat>(groupId, groupName, owner);
        return groupId;
    }
    
    void joinGroup(const std::string& groupId, const std::string& userId) {
        auto it = groupChats.find(groupId);
        if (it != groupChats.end()) {
            it->second->members.insert(userId);
        }
    }
    
    void sendGroupMessage(const std::string& groupId, const std::string& from, const std::string& content) {
        auto it = groupChats.find(groupId);
        if (it != groupChats.end()) {
            it->second->messages.emplace_back(from, content);
        }
    }
    
    std::shared_ptr<PrivateChat> getPrivateChat(const std::string& user1, const std::string& user2) {
        std::string chatId = (user1 < user2) ? user1 + "_" + user2 : user2 + "_" + user1;
        auto it = privateChats.find(chatId);
        return (it != privateChats.end()) ? it->second : nullptr;
    }
    
    std::shared_ptr<GroupChat> getGroup(const std::string& groupId) {
        auto it = groupChats.find(groupId);
        return (it != groupChats.end()) ? it->second : nullptr;
    }
};

void printSeparator(const std::string& title) {
    std::cout << "\n" << std::string(50, '=') << std::endl;
    std::cout << "  " << title << std::endl;
    std::cout << std::string(50, '=') << std::endl;
}

void demonstratePrivateChat(ChatComparison& chatSystem) {
    printSeparator("私聊 (P2P) 演示");
    
    // 用户登录
    chatSystem.addUser("Alice");
    chatSystem.addUser("Bob");
    std::cout << "✅ Alice 和 Bob 已上线" << std::endl;
    
    // 开始私聊
    std::string chatId = chatSystem.startPrivateChat("Alice", "Bob");
    std::cout << "📱 创建私聊会话: " << chatId << std::endl;
    
    // 发送消息
    chatSystem.sendPrivateMessage("Alice", "Bob", "Hi Bob, 你好吗？");
    std::cout << "💬 Alice -> Bob: Hi Bob, 你好吗？" << std::endl;
    
    chatSystem.sendPrivateMessage("Bob", "Alice", "我很好，谢谢！你呢？");
    std::cout << "💬 Bob -> Alice: 我很好，谢谢！你呢？" << std::endl;
    
    // 查看聊天记录
    auto chat = chatSystem.getPrivateChat("Alice", "Bob");
    if (chat) {
        std::cout << "\n📋 聊天记录 (" << chat->messages.size() << " 条消息):" << std::endl;
        for (const auto& msg : chat->messages) {
            std::cout << "  [" << msg.timestamp << "] " << msg.fromUser << ": " << msg.content << std::endl;
        }
    }
    
    std::cout << "\n🔍 私聊特点:" << std::endl;
    std::cout << "  • 点对点通信，只有两个参与者" << std::endl;
    std::cout << "  • 消息只在两个用户间传递" << std::endl;
    std::cout << "  • 聊天ID基于用户名生成 (Alice_Bob)" << std::endl;
    std::cout << "  • 消息历史保存在会话中" << std::endl;
    std::cout << "  • 时间复杂度: O(1)" << std::endl;
}

void demonstrateGroupChat(ChatComparison& chatSystem) {
    printSeparator("群聊 (Group) 演示");
    
    // 添加更多用户
    chatSystem.addUser("Charlie");
    chatSystem.addUser("David");
    std::cout << "✅ Charlie 和 David 已上线" << std::endl;
    
    // 创建群组
    std::string groupId = chatSystem.createGroup("技术讨论群", "Alice");
    std::cout << "🏠 Alice 创建群组: 技术讨论群 (ID: " << groupId << ")" << std::endl;
    
    // 用户加入群组
    chatSystem.joinGroup(groupId, "Bob");
    chatSystem.joinGroup(groupId, "Charlie");
    chatSystem.joinGroup(groupId, "David");
    std::cout << "👥 Bob, Charlie, David 已加入群组" << std::endl;
    
    // 群组信息
    auto group = chatSystem.getGroup(groupId);
    if (group) {
        std::cout << "📊 群组信息:" << std::endl;
        std::cout << "  • 群名: " << group->groupName << std::endl;
        std::cout << "  • 群主: " << group->ownerId << std::endl;
        std::cout << "  • 成员数: " << group->members.size() << std::endl;
    }
    
    // 发送群消息
    chatSystem.sendGroupMessage(groupId, "Alice", "欢迎大家加入技术讨论群！");
    chatSystem.sendGroupMessage(groupId, "Bob", "谢谢群主！");
    chatSystem.sendGroupMessage(groupId, "Charlie", "大家好！");
    chatSystem.sendGroupMessage(groupId, "David", "很高兴认识大家");
    
    std::cout << "\n💬 群聊消息:" << std::endl;
    std::cout << "  Alice: 欢迎大家加入技术讨论群！ → 广播给 3 人" << std::endl;
    std::cout << "  Bob: 谢谢群主！ → 广播给 3 人" << std::endl;
    std::cout << "  Charlie: 大家好！ → 广播给 3 人" << std::endl;
    std::cout << "  David: 很高兴认识大家 → 广播给 3 人" << std::endl;
    
    // 查看群消息历史
    if (group) {
        std::cout << "\n📋 群消息记录 (" << group->messages.size() << " 条消息):" << std::endl;
        for (const auto& msg : group->messages) {
            std::cout << "  [" << msg.timestamp << "] " << msg.fromUser << ": " << msg.content << std::endl;
        }
    }
    
    std::cout << "\n🔍 群聊特点:" << std::endl;
    std::cout << "  • 一对多通信，支持多个参与者" << std::endl;
    std::cout << "  • 消息广播给所有群成员" << std::endl;
    std::cout << "  • 有群主和管理员概念" << std::endl;
    std::cout << "  • 支持邀请、加入、离开机制" << std::endl;
    std::cout << "  • 群消息历史保存在群组中" << std::endl;
    std::cout << "  • 时间复杂度: O(n)，n为群成员数" << std::endl;
}

void demonstratePerformanceDifference() {
    printSeparator("性能对比分析");
    
    std::cout << "📊 消息传递复杂度对比:" << std::endl;
    std::cout << "┌────────────┬──────────┬──────────┬──────────┐" << std::endl;
    std::cout << "│    模式    │  时间复杂度  │  空间复杂度  │  网络开销  │" << std::endl;
    std::cout << "├────────────┼──────────┼──────────┼──────────┤" << std::endl;
    std::cout << "│   私聊     │   O(1)   │   O(1)   │    1x    │" << std::endl;
    std::cout << "│   群聊     │   O(n)   │   O(n)   │    nx    │" << std::endl;
    std::cout << "│ 全局广播   │   O(n)   │   O(n)   │    nx    │" << std::endl;
    std::cout << "└────────────┴──────────┴──────────┴──────────┘" << std::endl;
    
    std::cout << "\n🚀 性能特点:" << std::endl;
    std::cout << "私聊 (P2P):" << std::endl;
    std::cout << "  ✅ 消息传递最快，O(1) 时间复杂度" << std::endl;
    std::cout << "  ✅ 网络开销最小，只发送一次" << std::endl;
    std::cout << "  ✅ 服务器压力小" << std::endl;
    std::cout << "  ❌ 无法多人协作" << std::endl;
    
    std::cout << "\n群聊 (Group):" << std::endl;
    std::cout << "  ✅ 支持多人协作交流" << std::endl;
    std::cout << "  ✅ 有权限管理和组织结构" << std::endl;
    std::cout << "  ❌ 消息需要广播给 n 个用户" << std::endl;
    std::cout << "  ❌ 网络开销随成员数增长" << std::endl;
    
    std::cout << "\n全局广播 (当前基础系统):" << std::endl;
    std::cout << "  ❌ 消息发送给所有在线用户" << std::endl;
    std::cout << "  ❌ 无隐私保护" << std::endl;
    std::cout << "  ❌ 网络开销最大" << std::endl;
    std::cout << "  ❌ 无法精确控制接收者" << std::endl;
}

void demonstrateScenarios() {
    printSeparator("使用场景对比");
    
    std::cout << "🎯 私聊适用场景:" << std::endl;
    std::cout << "  • 一对一客服咨询" << std::endl;
    std::cout << "  • 私密敏感信息交流" << std::endl;
    std::cout << "  • 商务谈判对话" << std::endl;
    std::cout << "  • 朋友间的私人聊天" << std::endl;
    std::cout << "  • 医生患者咨询" << std::endl;
    
    std::cout << "\n🎯 群聊适用场景:" << std::endl;
    std::cout << "  • 团队协作讨论" << std::endl;
    std::cout << "  • 项目进度汇报" << std::endl;
    std::cout << "  • 技术交流群" << std::endl;
    std::cout << "  • 兴趣爱好社群" << std::endl;
    std::cout << "  • 公司部门群组" << std::endl;
    
    std::cout << "\n🎯 全局广播适用场景:" << std::endl;
    std::cout << "  • 系统公告通知" << std::endl;
    std::cout << "  • 紧急事件通报" << std::endl;
    std::cout << "  • 简单的聊天室" << std::endl;
    std::cout << "  • 游戏内全服喊话" << std::endl;
}

int main() {
    std::cout << "🚀 聊天系统架构对比演示" << std::endl;
    
    ChatComparison chatSystem;
    
    // 演示私聊
    demonstratePrivateChat(chatSystem);
    
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    
    // 演示群聊
    demonstrateGroupChat(chatSystem);
    
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    
    // 性能对比
    demonstratePerformanceDifference();
    
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    
    // 使用场景对比
    demonstrateScenarios();
    
    printSeparator("总结");
    std::cout << "📝 关键差异总结:" << std::endl;
    std::cout << "1. 📡 消息路由: 私聊是点对点，群聊是一对多广播" << std::endl;
    std::cout << "2. 👥 参与者: 私聊固定2人，群聊动态多人" << std::endl;
    std::cout << "3. 🔐 权限控制: 私聊无权限，群聊有管理员机制" << std::endl;
    std::cout << "4. 💾 存储结构: 私聊按对话存储，群聊按群组存储" << std::endl;
    std::cout << "5. 🚀 性能特征: 私聊O(1)，群聊O(n)" << std::endl;
    std::cout << "6. 🎯 应用场景: 私聊适合隐私，群聊适合协作" << std::endl;
    
    printSeparator("🎉 演示完成");
    std::cout << "现在您已经了解了私聊和群聊的区别，可以根据需求选择合适的聊天模式！" << std::endl;
    
    return 0;
} 